import React, { Component, Suspense } from 'react';
import PageLoading from '@/components/PageLoading';
import { Drawer, Button, Radio, Form, Result, notification, message, Table, Progress, Checkbox } from 'antd';
import {
  similarRecommendQuestiongetProcess, similarRecommendQuestiongetTaskInfo, similarRecommendQuestionsubmitTask,
  similarQuestionList, similarQuestionDelete, similarlibQuestionDelete
} from '@/services/similarExt';
// import QuestionLib from './QuestionLib';
import QuestionLib from './questionList';
import SystemQuestion from './systemQuestion';
import Styles from './index.less';

class Similar extends Component {
  state = {
    visible: false,
    process: null,
    taskInfo: null,
    timer: null,
    query: {
      size: 9999999,
      current: 1,
    },
    radio: '1',
    selectedRows: [],
    submited: false,
    targetKeys: [],
    qaType: null,
  };

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  componentWillUnmount() {
    const { timer } = this.state;
    if (timer) {
      clearTimeout(timer);
    }
  }

  showDrawer = (type) => {
    this.setState({ visible: true, qaType: type }, () => {
      this.getTaskInfo();
    });
  };

  onClose = () => {
    const { radio } = this.state;
    if (radio === '1') {
      this.delSimilarData();
    } else {
      this.delSimilarLibData();
    }
  };

  delSimilarData = async () => {
    const { onClose } = this.props;
    const { selectedRows } = this.state;
    const ids = selectedRows.map(item => item.id);
    const res = await similarQuestionDelete({ ids });
    onClose(selectedRows, 1);
    this.closeDreawer();
  };

  delSimilarLibData = async () => {
    const { onClose } = this.props;
    const { targetKeys, questions, rightData } = this.questionLibRef.state;
    let arr = rightData;
    // questions.records.forEach(item => {
    //   if (targetKeys.indexOf(item.id) > -1) {
    //     arr.push(item);
    //   }
    // });
    const ids = arr.map(item => item.id);
    if (ids.length > 0) {
      const res = await similarlibQuestionDelete({ ids });
      onClose(arr, 2);
      this.closeDreawer();
    }
  };

  getTaskInfo = async () => {
    const { questionId } = this.props;
    let { taskInfo } = this.state;
    taskInfo = await similarRecommendQuestiongetTaskInfo({ qaId: questionId });
    this.setState({ taskInfo }, () => {
      if (taskInfo.status === '0') {
        this.pollingForProcess();
      }
      if (taskInfo.status === '1') {
        this.getSimilars();
      }
    });
  };

  submitTask = async () => {
    const { questionId } = this.props;
    this.setState({ submited: true });
    const res = await similarRecommendQuestionsubmitTask({ qaId: questionId });
    console.log(res);
    if (res.status) {
      this.setState({ submited: false, taskInfo: { ...this.state.taskInfo, id: res.id, status: 0 }}, () => this.pollingForProcess());
    } else {
      this.setState({ submited: false })
      // return message.error(res.message);
    }
  };

  pollingForProcess = async () => {
    const { process, taskInfo } = this.state;
    let { timer } = this.state;
    if (taskInfo && !taskInfo.id) {
      return notification.open({
        message: '提示',
        description: '获取训练进度异常',
        type: 'error',
      });
    }
    if (!process || process.data !== 100) {
      this.setState({
        process: await similarRecommendQuestiongetProcess({ id: taskInfo.id }),
        submited: false,
      });
      timer = setTimeout(() => {
        this.pollingForProcess();
      }, 1000);
      this.setState({ timer });
    } else {
      this.setState({ taskInfo: { ...taskInfo, status: '1' } }, () => this.getSimilars());
      clearTimeout(timer);
    }
  };

  getSimilars = async () => {
    const { questionId } = this.props;
    let { similars } = this.state;
    const { query } = this.state;
    similars = await similarQuestionList({ qaId: questionId, ...query });
    this.setState({ similars });
  };

  handleRadioChange = e => {
    const { value } = e.target;
    let { radio } = this.state;
    const { timer } = this.state;
    radio = value;
    this.setState({ radio }, () => {
      if (radio === '1') {
        this.getTaskInfo();
      } else {
        clearTimeout(timer);
      }
    });
  };

  handlePagination = (current, size) => {
    let { query } = this.state;
    query.current = current;
    query.size = size;
    this.setState({ query }, () => this.getSimilars());
  };

  closeDreawer = () => {
    this.setState({ visible: false, radio: '1', submited: false }, () => {
      if (this.questionLibRef) {
        this.questionLibRef.onclose()
      }
    });
  };

  onQuestionLibChange = targetKeys => {
    this.setState({ selectedRows: targetKeys });
  };

  onCheckAllChange = () => {
    const { similars, selectedRows } = this.state;
    let data;
    if (selectedRows.length < similars?.records.length) {
      data = similars?.records;
    } else {
      data = [];
    }
    let selectedRowKeys = data.map(item => item.id);
    this.setState({ selectedRows: data, selectedRowKeys });
  }

  render() {
    const {
      visible, process, taskInfo, similars, radio,
      query, submited, selectedRows, selectedRowKeys,
    } = this.state;
    const { question, questionId, similarExtensionAsk } = this.props;
    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 14 },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 24, offset: 0 },
      },
    };
    const { current, size } = query;
    // rowSelection object indicates the need for row selection
    const rowSelection = {
      columnTitle: () => {
        return <Checkbox
          indeterminate={similars?.records.length !== this.state.selectedRows.length && this.state.selectedRows.length !== 0}
          onChange={this.onCheckAllChange}
          checked={similars?.records.length === this.state.selectedRows.length}
        >全选</Checkbox>
      },
      columnWidth: 100,
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRows, selectedRowKeys });
      },
    };
    const columns = [{
      title: '推荐相似问',
      dataIndex: 'question',
    }];

    return (
      <Drawer
        title="扩展相似问"
        placement="right"
        onClose={this.closeDreawer}
        visible={visible}
        closable
        width={840}
        zIndex={9999}
        destroyOnClose
      >
        <Suspense fallback={<PageLoading />}>
          <Form {...formItemLayout} onSubmit={this.handleSubmit}>
            <Form.Item label="扩展方式">
              <Radio.Group name="radiogroup" defaultValue={1} onChange={this.handleRadioChange}>
                <Radio value={1}>自动推荐</Radio>
                <Radio value={2}>从问题库中添加</Radio>
                <Radio value={3}>系统生成相似问</Radio>
              </Radio.Group>
            </Form.Item>

            {radio === 2 ? (
              <Form.Item label="" {...formItemLayoutWithOutLabel}>
                <Suspense fallback={<PageLoading />}>
                  <QuestionLib
                    onRef={ref => (this.questionLibRef = ref)}
                    qus={question}
                    onChange={this.onQuestionLibChange}
                  />
                </Suspense>
              </Form.Item>
            ) : radio === 3 ? (
              <Form.Item label="" {...formItemLayoutWithOutLabel}>
                <Suspense fallback={<PageLoading />}>
                  <SystemQuestion
                    onRef={ref => (this.SystemQuestionRef = ref)}
                    questionId={questionId}
                    qaType={this.state.qaType}
                    similarExtensionAsk={similarExtensionAsk}
                  />
                </Suspense>
              </Form.Item>
            ) : taskInfo && taskInfo.status === '2' ? (
              <Form.Item label="" {...formItemLayoutWithOutLabel}>
                <Result
                  subTitle="将'智能学习>知识库智能维护>问题库'中意思相近的问题推荐给该知识点"
                  extra={
                    <Button type="primary" onClick={this.submitTask} loading={submited}>开始推荐</Button>
                  }
                />
              </Form.Item>
            ) : taskInfo && taskInfo.status === '1' ? (
              similars && similars.records.length > 0 ? (
                <Form.Item label="" {...formItemLayoutWithOutLabel}>
                  <Table
                    rowKey="id"
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={similars?.records}
                    bordered
                    pagination={{
                      current,
                      pageSize: 9999999,
                      total: similars.total,
                      onChange: this.handlePagination,
                    }}
                    scroll={{ y: '70vh' }}
                  />
                </Form.Item>
              ) : (
                <Form.Item label="" {...formItemLayoutWithOutLabel}>
                  <Result
                    status="warning"
                    title="抱歉，没有找到合适的推荐问题"
                    subTitle="您可以在'智能学习>知识库智能维护>问题库'中多导入一些相关问题再进行推荐"
                    extra={
                      <Button type="primary" onClick={this.submitTask} loading={submited}>重新推荐</Button>
                    }
                  />
                </Form.Item>
              )
            ) : (
              <Form.Item label="" {...formItemLayoutWithOutLabel} style={{ textAlign: 'center', paddingTop: 100 }}>
                <Progress type="circle" percent={process?.data} />
                <p>问题推荐中...</p>
              </Form.Item>
            )}
          </Form>
        </Suspense>
        {radio === 3 ? '' : (
          <div style={{ position: 'absolute', right: 0, bottom: 0, width: '100%', borderTop: '1px solid #e9e9e9', padding: '10px 16px', background: '#fff', textAlign: 'right', }}>
            <Button onClick={this.submitTask} style={{ marginRight: 8 }} disabled={radio !== 1}>重新推荐</Button>
            <Button
              onClick={this.onClose}
              type="primary"
              disabled={(taskInfo && taskInfo.status === 2) || !taskInfo || selectedRows.length === 0}
            >添加到知识点</Button>
          </div>
        )}
      </Drawer>
    );
  }
}

export default Form.create()(Similar);
